<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="searchProduct.typeId" placeholder="产品类型" clearable>
          <el-option
            v-for="item in allProductType"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchProduct.modelId" clearable placeholder="请选择型号">
          <el-option
            v-for="item in allModel"
            :key="item.id"
            :label="item.code"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchProduct.brandId" clearable placeholder="请选择品牌">
          <el-option
            v-for="item in allBrand"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/产品导入模板.xlsx" download="产品导入模板.xlsx" style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载</el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <custom-table
      :columns="columns"
      :data="productList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 产品模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType ==='add'? '新增产品':'修改产品信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :model="productDto" :rules="productRules" label-width="110px" ref="productForm">
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="productDto.brandId" placeholder="请选择品牌" @change="brandChange">
            <el-option
              v-for="item in brandOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model="productDto.modelId" placeholder="请选择型号">
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.code"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <!--<el-input v-model.trim="productDto.name" auto-complete="off"></el-input>-->
          <el-select v-model="productDto.typeId" placeholder="请选择产品类型">
            <el-option
              v-for="item in allProductType"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" v-model.number="productDto.price" auto-complete="off"
                    @change="checkPrice(productDto.price)"></el-input>
        </el-form-item>
        <el-form-item label="保修条件" prop="status">
          <el-select v-model="productDto.status" placeholder="请选择保修起始条件">
            <el-option :key="0" label="激活日期" :value="0"></el-option>
            <el-option :key="1" label="发货日期" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保修期限(天)" prop="deadLine">
          <el-input-number type="number" v-model.number="productDto.deadLine" :min="1" :step="1">
          </el-input-number>
        </el-form-item>
        <el-form-item label="生产工厂" prop="factoryId">
          <el-select v-model="productDto.factoryId" placeholder="请选择生产工厂">
            <el-option
              v-for="item in manuFactoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="芯片厂商" prop="chipFactoryId">
          <el-select v-model="productDto.chipFactoryId" placeholder="请选择芯片厂商">
            <el-option
              v-for="item in chipFactoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiProductReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {
    apiGetModelList,
    apiGetBrandList,
    apiGetChipFactoryList,
    apiGetFactoryList,
    apiGetProductType
  } from '@/api/dictionary'
  import {
    apiGetProductList,
    apiGetProductById,
    apiDelProduct,
    apiAddProduct,
    apiUpdProduct,
    apiExport
  } from '@/api/basic/info/product'
  import {baseInfo} from '@/utils/fetch'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'product',
    components: {CustomTable},
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getProductList(listQuery)
      this.getAllModel()
      this.getAllBrand()
      this.getAllProductType()
      let factoryQuery = {
        pageNumber: 1,
        pageSize: 100,
        factoryType: 0
      }
      this.getFactoryList(factoryQuery)
      factoryQuery.factoryType = 1
      this.getChipFactoryList(listQuery)
    },
    data () {
      var checkNum = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('价格不能为空'))
        }
        setTimeout(() => {
          if (value < 1) {
            callback(new Error('必须大于1'))
          } else {
            callback()
          }
        }, 1000)
      }
      var checkDate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('保修期限不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入整数值'))
          } else {
            if (value < 1) {
              callback(new Error('必须大于1'))
            } else {
              callback()
            }
          }
        }, 1000)
      }
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        dialogVisible: false,
        wrongDataList: [],
        hideTable: false,
        uploadVisible: false,
        dialogType: undefined,
        manuFactoryList: [],
        chipFactoryList: [],
        filePath: '',
        searchProduct: {
          typeId: '',
          modelId: '',
          brandId: ''
        },
        listQuery: {
          typeId: undefined,
          model: undefined,
          brand: undefined
        },
        allModel: [],
        allProductType: [],
        allBrand: [],
        productDto: {
          brandId: undefined,
          modelId: undefined,
          productType: '',
          typeId: '',
          price: undefined,
          status: undefined,
          deadLine: undefined,
          chipFactoryId: undefined,
          factoryId: undefined
        },
        brandOptions: this.getBrandList(),    // 品牌类型
        modelOptions: [],
        productRules: {
          brandId: [{type: 'number', required: true, message: '请选择品牌', trigger: 'change'}],
          modelId: [{type: 'number', required: true, message: '请选择型号', trigger: 'change'}],
          chipFactoryId: [{type: 'number', required: true, message: '请选择芯片厂商', trigger: 'change'}],
          price: [{type: 'number', required: true, message: '请输入价格', trigger: 'blur'},
            {type: 'number', message: '价格必须是数字', trigger: 'blur'},
            {validator: checkNum, trigger: 'blur'}],
          name: [{required: true, message: '请输入产品名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}],
          status: [{type: 'number', required: true, message: '请选择保修起始条件', trigger: 'change'}],
          deadLine: [{type: 'number', required: true, message: '请输入保修期限', trigger: 'blur'},
            {type: 'number', message: '保修期限必须是数字', trigger: 'blur'},
            {validator: checkDate, trigger: 'blur'}]
        },
        tableLoadingFlag: false,                  // 产品一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '产品类型', name: 'productType', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', width: '120', align: 'center'},
          {label: '价格(元)', name: 'price', align: 'center'},
          {label: '保修起始条件', name: 'status', width: '120', align: 'center', formatter: this.formatStatus},
          {label: '保修期限(天)', name: 'deadLine', width: '120', align: 'center'},
          {label: '芯片厂商', name: 'chipFactoryName', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '产品类型', name: 'productType', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: '价格', name: 'price', align: 'center'},
          {label: '保修起始条件', name: 'status', align: 'center'},
          {label: '保修期限(天)', name: 'deadLine', align: 'center'},
          {label: '芯片厂商', name: 'chipFactory', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        productList: [],
        pagination: this.getData(this.getProductList)
      }
    },

    methods: {
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      excelExport () {
        let paramsPost = {
          modelId: this.searchProduct.modelId,
          brandId: this.searchProduct.brandId,
          typeId: this.searchProduct.typeId
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后产品信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead (filePath) {
        apiProductReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getProductList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      getFactoryList (listQuery) {
        apiGetFactoryList(listQuery).then(response => {
          this.manuFactoryList = response.data
        }).catch(() => {
          this.$message({showClose: true, message: '获取生产工厂列表失败', type: 'error'});
        })
      },
      getChipFactoryList (listQuery) {
        apiGetChipFactoryList(listQuery).then(response => {
          this.chipFactoryList = response.data
        }).catch(() => {
          this.$message({showClose: true, message: '获取芯片厂商列表失败', type: 'error'});
        })
      },
      formatStatus (row, column, cellValue) {
        if (cellValue === 1) {
          return '发货日期'
        }
        return '激活日期'
      },
      getProductList (listQuery) {
        if (listQuery.typeId === undefined) {
          listQuery.typeId = this.searchProduct.typeId
        }
        if (listQuery.model === undefined) {
          listQuery.model = this.searchProduct.modelId
        }
        if (listQuery.brand === undefined) {
          listQuery.brand = this.searchProduct.brandId
        }
        this.listLoadingFlag = true
        apiGetProductList(listQuery).then(response => {
          this.productList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.listLoadingFlag = false
        }).catch(() => {
          this.listLoadingFlag = false
        })
      },
      getAllModel () {
        apiGetModelList().then(response => {
          this.allModel = response.data
        })
      },
      getAllProductType () {
        apiGetProductType().then(response => {
          this.allProductType = response.data
        })
      },
      getAllBrand () {
        apiGetBrandList().then(response => {
          this.allBrand = response.data
        })
      },
      handleAdd () {
        this.dialogType = 'add'
        this.dialogVisible = true
        this.productDto = {
          brandId: undefined,
          modelId: undefined,
          productType: '',
          typeId: undefined,
          price: undefined,
          status: undefined,
          deadLine: undefined,
          chipFactoryId: undefined,
          factoryId: undefined
        }
        if (this.$refs['productForm']) {
          this.$refs['productForm'].resetFields()
        }
      },
      handleEdit (row) {
        apiGetProductById(row.id).then(response => {
          let data = response.data
          this.productDto = {
            id: row.id,
            brandId: data.brandId,
            modelId: undefined,
            productType: data.productType,
            typeId: data.typeId,
            price: data.price,
            status: data.status,
            deadLine: data.deadLine,
            chipFactoryId: data.chipFactoryId
          }
          this.productDto.factoryId = data.factoryId
          this.pagination.totalRecords = response.totalRecords
          var that = this
          var search = this.getModelList({brandId: data.brandId})
          var res = search.then(function (value) {
            that.modelOptions = value
            value.forEach(function (item) {
              if (item.id == data.modelId) {
                that.productDto.modelId = data.modelId
              }
            })
          }, function (value) {
          })
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },

      brandChange (val) {
        var that = this;
        var search = this.getModelList({brandId: val})
        var flag = 0
        var res = search.then(function (value) {
          that.modelOptions = value
          if (that.productDto.id == null || that.productDto.id == undefined) {
            that.productDto.modelId = undefined
          } else {
            var oldModleId = that.productDto.modelId;
            that.productDto.modelId = undefined
            value.forEach(function (item) {
              if (item.id == oldModleId) {
                that.productDto.modelId = oldModleId;
              }
            });
          }
        }, function (value) {

        });
      },
      handleDel (row) {
        this.$confirm('确定删除该产品?', '删除产品', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelProduct(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getProductList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      submit () {
        this.$refs.productForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddProduct(this.productDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getProductList(this.listQuery)
        })
      },
      updSubmit () {
        apiUpdProduct(this.productDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getProductList(this.listQuery)
        })
      },
      cancel () {
        this.dialogVisible = false
        this.$refs.productForm.resetFields()
      },
      searchData () {
        this.listQuery.typeId = this.searchProduct.typeId
        this.listQuery.brand = this.searchProduct.brandId
        this.listQuery.model = this.searchProduct.modelId
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getProductList(this.listQuery)
      }
    }
  }
</script>
